package com.example.myshools.Mine.organization.edit;


import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.myshools.Mine.organization.publish.IdentificationResult;
import com.example.myshools.R;
import com.example.myshools.entity.Constant;
import com.example.myshools.entity.Orgnaization;
import com.example.myshools.util.GlideEngine;
import com.example.myshools.util.InputTextDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.language.LanguageConfig;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PersonalData extends AppCompatActivity implements View.OnClickListener {
    private TextView img_upload_tip;//修改头像
    private TextView name_tip;//修改名字
    private TextView o_information_tip;//资料简介
    private TextView renZ_img_up_tip;//认证图片上传
    private TextView lianxi_up_tip;//联系方式更改
    private Boolean renZStatues = false;//默认为false，修改组织认证资料的时候设为1
    private Boolean nameStatus = false;
    private TextView o_name;
    private ImageView o_img;
    private TextView o_information;
    private TextView o_ren_z;
    private TextView lian_xi;
    private Button up_data;
    private Button return_mine;
    private Orgnaization orgnaization;
    private PictureWindowAnimationStyle mWindowAnimationStyle;//相册启动动画
    private List<LocalMedia> result = new ArrayList<>();
    private InputTextDialog inputTextDialog;//文字输入框
    private OkHttpClient okHttpClient = new OkHttpClient();
    private int id;//userId
    private Boolean nowStatus;
    private int who;
    private Boolean isup = false;//设置信息是否更改


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mine_data);

        String s = getIntent().getStringExtra("o");
        Gson gson = new Gson();
        orgnaization = gson.fromJson(s, Orgnaization.class);
        id = orgnaization.getId();
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }
        findView();
        setView();
        setListener();
    }


    private void findView() {
        return_mine = findViewById(R.id.btn_return_setting);

        o_name = findViewById(R.id.o_name);

        o_img = findViewById(R.id.o_img);

        o_information = findViewById(R.id.o_information);
        o_ren_z = findViewById(R.id.renz_ziliao);
        lian_xi = findViewById(R.id.lian_xi_content);
        up_data = findViewById(R.id.up_data);
        up_data.setEnabled(false);//初始化时使验证按钮不可点击
        //头像修改成功后显示
        img_upload_tip = findViewById(R.id.img_upload_tip);
        //名字修改成功后显示
        name_tip = findViewById(R.id.up_name_tip);
        //修改资料成功后显示
        o_information_tip = findViewById(R.id.o_information_upload_tip);
        //认证图片修改
        renZ_img_up_tip = findViewById(R.id.ren_zheng_upload_tip);
        //联系方式更改后
        lianxi_up_tip = findViewById(R.id.lian_xi_content_upload_tip);


    }


    private void setView() {
        o_name.setText(orgnaization.getName());
        if(orgnaization.getHeadPath().length()>0) {
            RequestOptions requestOptions = new RequestOptions().placeholder(R.drawable.loading).error(R.drawable.headfail).fallback(R.drawable.loading).diskCacheStrategy(DiskCacheStrategy.ALL).circleCrop();
            Glide.with(this).load(orgnaization.getHeadPath()).apply(requestOptions).into(o_img);
        }
        o_information.setText(orgnaization.getRecommend());
        o_ren_z.setText(orgnaization.getIdentityContent());
        lian_xi.setText(orgnaization.getConnectionContent());


    }


    private void setListener() {
        //返回
        return_mine.setOnClickListener(this::onClick);
        //名字修改
        o_name.setOnClickListener(this::onClick);
        //头像点击修改：
        o_img.setOnClickListener(this::onClick);
        //资料简介修改
        o_information.setOnClickListener(this::onClick);

        o_ren_z.setOnClickListener(this::onClick);
        //联系方式
        lian_xi.setOnClickListener(this::onClick);

        //开始认证
        up_data.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.o_img:
                //打开图片选择器
                img_upload_tip.setText("");
                nowStatus = true;
                who = 1; //因为之前认证资料是上传图片，所以设置了who:哪个照片（认证照片还是头像照片）
                openPictureSelect();
                break;
            case R.id.renz_ziliao:
                //修改认证资料
                renZ_img_up_tip.setText("");
                inputTextDialog = new InputTextDialog(PersonalData.this, R.style.dialog_center, 255);
                String hint0 = "";
                if (o_ren_z.getText().length()>0) {
                    hint0 = o_ren_z.getText().toString();
                } else {
                    hint0 = "您需要输入组织的上级单位，组织负责人及联系方式（如果您不是组织负责人，需要标注您的联系方式），以及方便为您认证的其他信息（选填），便于我们的审核认证";
                }

                inputTextDialog.setHint(hint0);
                inputTextDialog.setMaxNumber(255);//最长字数
                inputTextDialog.show();
                String finalHint = hint0;
                inputTextDialog.setmOnTextSendListener(msg -> {
                    o_ren_z.setText(msg);
                    //数据库修改
                    String s=msg.toString();
                    if(!s.equals(finalHint)){
                        upDataIdentityContent(msg);
                    }

                });
                break;
            case R.id.lian_xi_content:
                lianxi_up_tip.setText("");
                inputTextDialog = new InputTextDialog(PersonalData.this, R.style.dialog_center, 255);
                String hint1 = "";
                if (lian_xi.getText().toString().length() > 0) {
                    hint1 = lian_xi.getText().toString();
                } else {
                    hint1 = "建议修改文本后复制粘贴到这里";
                }

                inputTextDialog.setHint(hint1);
                inputTextDialog.setMaxNumber(255);//最长字数
                inputTextDialog.show();
                inputTextDialog.setmOnTextSendListener(msg -> {
                    lian_xi.setText(msg);
                    //数据库修改
                    updateConnect(msg);
                });
                break;


            case R.id.btn_return_setting:
                //EventBus.getDefault().post(new Message());
                finish();
                break;
            case R.id.o_name:
                name_tip.setText("");
                inputTextDialog = new InputTextDialog(PersonalData.this, R.style.dialog_center, 20);
                String hint = "";
                if (o_name.getText().toString().length() > 0) {
                    hint = o_name.getText().toString();
                } else {
                    hint = "请输入组织名字";
                }
                inputTextDialog.setHint(hint);
                inputTextDialog.setMaxNumber(20);//最长十个字
                inputTextDialog.show();
                inputTextDialog.setmOnTextSendListener(msg -> {
                    o_name.setText(msg);
                    //数据库修改
                    upDataOName(msg);
                });
                break;
            case R.id.o_information:
                o_information_tip.setText("");
                inputTextDialog = new InputTextDialog(PersonalData.this, R.style.dialog_center, 2048);
                String hint2 = "";
                if (o_information.getText().toString().length() > 0) {
                    hint2 = o_information.getText().toString();
                } else {
                    hint2 = "建议修改文本后复制粘贴到这里";
                }
                inputTextDialog.setHint(hint2);
                inputTextDialog.setMaxNumber(2048);//最长十个字
                inputTextDialog.show();
                inputTextDialog.setmOnTextSendListener(msg -> {
                    o_information.setText(msg);
                    //数据库修改
                    updateInformation(msg);
                });
                break;


            case R.id.up_data:
                /*
                 * 1当组织名字更改时，有认证资料，需要重新认证，没有资料无需认证，提示
                 * 2当组织资质证书更改时，有名字则开始认证，无名则提示
                 * */
                if (renZStatues || nameStatus) {
                    Log.e("sss=================", "ssssssssssssss");
                    if (orgnaization.getName().length() < 1) {
                        Toast.makeText(PersonalData.this, "名字为空，无法认证", Toast.LENGTH_SHORT).show();
                    }
                    if (orgnaization.getIdentityContent().length() < 1) {
                        Toast.makeText(PersonalData.this, "资质证书无效，无法认证", Toast.LENGTH_SHORT).show();
                    }
                    if (orgnaization.getName().length() > 0 && orgnaization.getIdentityContent().length() > 0) {
                        //向服务器发送认证请求，将认证status设为2
                        up_data.setEnabled(false);
                        up_data.setBackgroundColor(Color.parseColor("#bfbfbf"));
                        up_data.setText("正在发送请求");
                        sendIdentityRequest(0, id);

                    }
                    break;
                }


        }

    }
    //修改认证资料
    private void upDataIdentityContent(String msg) {
        renZ_img_up_tip.setText("修改中..");
        FormBody.Builder builder = new FormBody.Builder().add("identityContent", msg).add("id", String.valueOf(id));
        FormBody body = builder
                .build();
        Request request = new Request.Builder()
                .post(body)
                .url(Constant.url + "user/updateOrgIdentityContentById")
                .build();
        final Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 12;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功 succeed ，，获取返回数据时 回调此方法
                String str = response.body().string();
                Message message = new Message();
                int s= Integer.parseInt(str);
                if(s!=1){
                    message.what=13;//更改失败
                }else {
                    message.what=14;//认证资料更改成功
                }
                handler.sendMessage(message);
            }
        });

    }

    private void sendIdentityRequest(int role, int id) {
        FormBody.Builder builder = new FormBody.Builder().add("role", String.valueOf(role)).add("id", String.valueOf(id)).add("status", String.valueOf(2));
        FormBody body = builder
                .build();

        Request request = new Request.Builder()
                .post(body)
                .url(Constant.url + "user/updateIdentityById")
                .build();
        final Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                up_data.setEnabled(true);
                up_data.setText("开始认证");
                Message message = new Message();
                message.what = 10;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功 succeed ，，获取返回数据时 回调此方法
                String jsonStr = response.body().string();

                Message message = new Message();
                message.what = 11;
                message.obj = jsonStr;
                handler.sendMessage(message);


            }
        });

    }

    //修改联系方式
    private void updateConnect(String msg) {
        lianxi_up_tip.setText("修改中..");
        FormBody.Builder builder = new FormBody.Builder().add("connect", msg).add("id", String.valueOf(id));
        FormBody body = builder
                .build();

        Request request = new Request.Builder()
                .post(body)
                .url(Constant.url + "user/updateOrgConnectById")
                .build();
        final Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 5;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功 succeed ，，获取返回数据时 回调此方法
                String jsonStr = response.body().string();
                Message message = new Message();
                message.what = 9;
                message.obj = jsonStr;
                handler.sendMessage(message);
            }
        });


    }

    //修改组织简介
    private void updateInformation(String msg) {
        o_information_tip.setText("修改中..");
        FormBody.Builder builder = new FormBody.Builder().add("recommend", msg).add("id", String.valueOf(id));
        FormBody body = builder
                .build();

        Request request = new Request.Builder()
                .post(body)
                .url(Constant.url + "user/updateOrgCommById")
                .build();
        final Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 6;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功 succeed ，，获取返回数据时 回调此方法
                String jsonStr = response.body().string();
                Message message = new Message();
                message.what = 7;
                message.obj = jsonStr;
                handler.sendMessage(message);
            }
        });


    }

    //修改组织名字
    private void upDataOName(String msg) {
        name_tip.setText("修改中..");
        FormBody.Builder builder = new FormBody.Builder().add("name", msg).add("id", String.valueOf(id));
        FormBody body = builder
                .build();

        Request request = new Request.Builder()
                .post(body)
                .url(Constant.url + "user/updateOrgNameById")
                .build();
        final Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 5;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功 succeed ，，获取返回数据时 回调此方法
                String jsonStr = response.body().string();
                Message message = new Message();
                message.what = 3;
                message.obj = jsonStr;
                handler.sendMessage(message);
            }
        });
    }

    private void openPictureSelect() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//相册 媒体类型 PictureMimeType.ofAll()、ofImage()、ofVideo()、ofAudio()
                //.openCamera()//单独使用相机 媒体类型 PictureMimeType.ofImage()、ofVideo()
                .theme(R.style.picture_default_style)// xml样式配制 R.style.picture_default_style、picture_WeChat_style or 更多参考Demo
                .loadImageEngine(GlideEngine.createGlideEngine())// 图片加载引擎 需要 implements ImageEngine接口
                .selectionMode(PictureConfig.SINGLE)//单选or多选 PictureConfig.SINGLE PictureConfig.MULTIPLE
                .isPageStrategy(false)//开启分页模式，默认开启另提供两个参数；pageSize每页总数；isFilterInvalidFile是否过滤损坏图片
                // .isSingleDirectReturn(true)//PictureConfig.SINGLE模式下是否直接返回
                // .isWeChatStyle()//开启R.style.picture_WeChat_style样式
                //.setPictureStyle()//动态自定义相册主题
                //.setPictureCropStyle()//动态自定义裁剪主题
                .setPictureWindowAnimationStyle(mWindowAnimationStyle)//相册启动退出动画
                .isCamera(false)//列表是否显示拍照按钮
                //.isZoomAnim(pi)//图片选择缩放效果
                // .imageFormat()//拍照图片格式后缀,默认jpeg, PictureMimeType.PNG，Android Q使用PictureMimeType.PNG_Q
                .maxSelectNum(1)//最大选择数量,默认9张
                .minSelectNum(1)// 最小选择数量
                .compress(true)//是否压缩
                .compressFocusAlpha(true)//压缩后是否保持图片的透明通道
                .minimumCompressSize(0)// 小于多少kb的图片不压缩
                .imageSpanCount(4)//列表每行显示个数
                .openClickSound(false)//是否开启点击声音
                .selectionMedia(result)//是否传入已选图片

                .previewImage(true)//是否预览图片
                .enableCrop(nowStatus)//是否开启裁剪

                .freeStyleCropEnabled(true)//裁剪框是否可拖拽
                .circleDimmedLayer(nowStatus)// 是否开启圆形裁剪
                .setCircleDimmedBorderColor(R.color.textColorBlue)//设置圆形裁剪边框色值
                .setCircleStrokeWidth(2)//设置圆形裁剪边框粗细
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)//是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .rotateEnabled(false)//裁剪是否可旋转图片
                .scaleEnabled(true)//裁剪是否可放大缩小图片
                .isDragFrame(true)//是否可拖动裁剪框(固定)
                .hideBottomControls(false)//显示底部uCrop工具栏


                .setLanguage(LanguageConfig.CHINESE)//国际化语言 LanguageConfig.CHINESE、ENGLISH、JAPAN等

                .isMaxSelectEnabledMask(true)//选择条件达到阀时列表是否启用蒙层效果
                .forResult(new MyResultCallback());//结果回调分两种方式onActivityResult()和OnResultCallbackListener方式
    }

    private class MyResultCallback implements OnResultCallbackListener<LocalMedia> {

        @Override
        public void onResult(List<LocalMedia> result1) {
            result = result1;

            //上传服务器
            /*  int id=getSharedPreferences("user")*/
            Message message = new Message();
            message.what = 2;
            message.obj = result.get(0).getCompressPath();
            handler.sendMessage(message);
            upLoad();
        }

        @Override
        public void onCancel() {

        }
    }

    private void upLoad() {
        if(who==1){
            img_upload_tip.setText("上传中..");
        }
        if (who==2) {
            renZ_img_up_tip.setText("正在上传...");
        }
        int role = 0;
        File file = new File(result.get(0).getCompressPath());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);//把文件与类型放入请求体
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM)
                .addFormDataPart("userId", String.valueOf(id)).addFormDataPart("role", String.valueOf(role)).addFormDataPart("who", String.valueOf(who));
        if (file.exists()) {
            builder.addFormDataPart("file", file.getName(), requestBody);//文件名,请求体里的文件
        }
        MultipartBody multipartBody = builder.build();

        Request request = new Request.Builder()
                .url(Constant.url + "photo/updateUserImgPath")
                .post(multipartBody)
                .build();
        final Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 4;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功 succeed ，，获取返回数据时 回调此方法
                String jsonStr = response.body().string();
                Log.e("jsonstrqqqqqqqqq", jsonStr);
                Gson gson = new Gson();
                Map map = new HashMap();
                map = gson.fromJson(jsonStr, new TypeToken<Map>() {
                }.getType());
                String res = map.get("result").toString();
                String w = map.get("who").toString();

                Message message = new Message();
                if (res.equals("ok")) {//更改返回结果表示ok为成功
                    if (w.equals("one")) {
                        message.what = 1;//头像
                    }else {
                        message.what = 8;//验证
                    }
                }else {

                }
                message.obj = jsonStr;
                handler.sendMessage(message);


            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                img_upload_tip.setText("上传成功");
            }
            if (msg.what == 2) {
                if (who == 1) {
                    RequestOptions requestOptions = new RequestOptions().circleCrop();
                    Glide.with(PersonalData.this).load(msg.obj.toString()).apply(requestOptions).into(o_img);
                } else if (who == 2) {
                    up_data.setEnabled(true);//更改资质证书成功时验证可点击
                    up_data.setBackgroundColor(Color.parseColor("#1296db"));
                    isup = true;
                    renZStatues = true;
                    orgnaization.setIdentityContent(msg.obj.toString());
                }
            }
            if (msg.what == 3) {
                //更改组织名字
                nameStatus = true;
                orgnaization.setName(o_name.getText().toString());
                up_data.setEnabled(true);//更改组织名字成功时验证可点击
                up_data.setBackgroundColor(Color.parseColor("#1296db"));
                isup = true;
                name_tip.setText("成功");
            }
            if (msg.what == 4) {
                img_upload_tip.setText("请重新上传");
                Toast.makeText(PersonalData.this, "网络错误,头像上传失败", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 5) {
                name_tip.setText("失败");
                Toast.makeText(PersonalData.this, "网络错误,更改失败", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 6) {
                o_information_tip.setText("修改失败");
                Toast.makeText(PersonalData.this, "网络错误,资料更改失败", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 7) {
                o_information_tip.setText("修改成功");
            }

            if (msg.what == 9) {
                lianxi_up_tip.setText("修改成功");
            }
            if (msg.what == 10) {
                Toast.makeText(PersonalData.this, "网络连接失败", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 11) {
                Log.e("sss=================", "返回值");
                int re = Integer.parseInt(msg.obj.toString());
                if (re == 1) {
                    Intent intent = new Intent(PersonalData.this, IdentificationResult.class).putExtra("status", 2);
                    startActivity(intent);
                   // EventBus.getDefault().post(new Message());
                    finish();
                } else {
                    Toast.makeText(PersonalData.this, "在设置中反馈", Toast.LENGTH_SHORT).show();

                }
            }
            if (msg.what == 12) {
                renZ_img_up_tip.setText("修改失败");
                Toast.makeText(PersonalData.this, "网络连接失败", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 13) {//认证资料更改失败
                renZ_img_up_tip.setText("修改失败");

            } if (msg.what == 14) {//认证资料更改成功
                renZ_img_up_tip.setText("修改成功");
                up_data.setEnabled(true);//更改资质证书成功时验证可点击
                up_data.setBackgroundColor(Color.parseColor("#1296db"));
                isup = true;
                renZStatues = true;
            }
        }
    };


}